package com.pliu.config;

import com.pliu.pojo.Configuration;
import com.pliu.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * @ClassName XMLMapperBuilder
 * @Description mapper解析类
 * @Author pliu
 * @Date 2020/6/21 14:15
 * @Version 1.0
 **/
public class XMLMapperBuilder {
    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream is) throws Exception {
        Document document = new SAXReader().read(is);
        Element rootElement = document.getRootElement();
        parseNode(rootElement.selectNodes("//select"),rootElement);
        parseNode(rootElement.selectNodes("//insert"),rootElement);
        parseNode(rootElement.selectNodes("//update"),rootElement);
        parseNode(rootElement.selectNodes("//delete"),rootElement);
    }

    /**
     * 解析节点封装成mappedStatement,保存到configuration的MappedStatementMap
     * @param list
     * @param rootElement
     */
    private void parseNode(List<Element> list,Element rootElement) {
        for (Element element : list) {
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(element.attributeValue("id"));
            mappedStatement.setResultType(element.attributeValue("resultType"));
            mappedStatement.setParamterType(element.attributeValue("paramterType"));
            mappedStatement.setSql(element.getTextTrim());
            String key = rootElement.attributeValue("namespace")+"."+element.attributeValue("id");
            configuration.getMappedStatementMap().put(key, mappedStatement);
        }
    }
}
